package cxy.highConcurrency;

import java.util.concurrent.CompletionService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 使用 CompletionService 实现了一个询价应用的核心功能，后来又有了新的需求，需要计算出最低报价并返回，
 * @author admin
 *
 */
public class CompletionServiceDemo_2 {
	public static void main(String[] args) throws InterruptedException {

		// 创建线程池
		ExecutorService executor = Executors.newFixedThreadPool(3);
		// 创建CompletionService
		CompletionService<Integer> cs = new ExecutorCompletionService<>(executor);
		// 异步向电商S1询价
		cs.submit(() -> getPriceByS1());
		// 异步向电商S2询价
		cs.submit(() -> getPriceByS2());
		// 异步向电商S3询价
		cs.submit(() -> getPriceByS3());
		// 将询价结果异步保存到数据库
		// 并计算最低报价
		AtomicReference<Integer> m = new AtomicReference<>(Integer.MAX_VALUE);
		CountDownLatch countDownLatch = new CountDownLatch(3);
		for (int i = 0; i < 3; i++) {
			executor.execute(() -> {
				Integer r = null;
				try {
					r = cs.take().get();
				} catch (Exception e) {
				}
				System.out.println("r:" + r);
				m.set(Integer.min(m.get(), r));
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		System.out.println("m:" + m);
		executor.shutdown();
		return;
	}

	static int getPriceByS1() {
		System.out.println("geocoderByS1");
		sleep(1, TimeUnit.SECONDS);
		return 1;
	}

	static int getPriceByS2() {
		System.out.println("geocoderByS2");
		sleep(1, TimeUnit.SECONDS);
		return 2;
	}

	static int getPriceByS3() {
		System.out.println("geocoderByS3");
		sleep(1, TimeUnit.SECONDS);
		return 3;
	}

	static void sleep(int t, TimeUnit u) {
		try {
			u.sleep(t);
		} catch (InterruptedException e) {
		}
	}
}
